import datetime
import json

from django.contrib import auth
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.db.models import Sum
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, render, redirect
from roll.models import Wheel
import time

# 白班/夜班时间
day = 7
night = 19


# 格式时间
def dt():
    dt = time.localtime(time.time())
    day_or_night = '白班' if int(day <= dt.tm_hour <= 19) else '夜班'
    m_date = '%s年%s月%s日 %s时%s分' % (dt.tm_year, dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min)
    return m_date, day_or_night


def index(request):
    # 时间
    m_date, day_or_night = dt()
    return render(request, 'index.html', {'time': m_date, 'day_or_night': day_or_night})


def add(request):
    # ng = {'ng_1': '铸造不良', 'ng_2': '加工不良'}
    if request.method == 'POST':
        if not request.user.is_authenticated:
            # print('需要登录')
            return HttpResponse(json.dumps({'success': False, 'e': '需要登录'}), content_type='Application/json')

        ng_1 = request.POST['ng_1']
        ng_2 = request.POST['ng_2']
        ng_3 = request.POST['ng_3']
        result = {'success': True}
        # 保存
        try:
            w = Wheel()
            w.n_casting = int(ng_1)
            w.n_machining = int(ng_2)
            w.n_coating = int(ng_3)
            w.n_sum = w.n_casting + w.n_machining + w.n_coating
            w.user = request.user
            w.save()
        except Exception as e:
            print(e)
            result['success'] = False
            result['e'] = str(e)
        return HttpResponse(json.dumps(result), content_type='Application/json')


# 登录
def login(request):
    result = {'success': True}
    if request.method == 'POST':
        user = authenticate(username=request.POST['user'], password=request.POST['password'])
        if user is not None and user.is_active:
            auth.login(request, user)
        else:
            result['success'] = False
        return HttpResponse(json.dumps(result), content_type='Application/json')

    if request.method == 'GET':
        return render(request, 'login.html')


# 日报表
def report_day(request):
    # 取时间
    dt = datetime.datetime.now()

    dt_start = datetime.datetime(int(dt.year), int(dt.month), int(dt.day), 7, 0, 0)
    dt_end = datetime.datetime(int(dt.year), int(dt.month), int(dt.day), 19, 59, 59)
    query = Wheel.objects.filter(put_at__range=[dt_start, dt_end]).order_by('put_at')
    data_casting = [[str(q.put_at), q.n_casting] for q in query]
    data_machining = [[str(q.put_at), q.n_machining] for q in query]
    data_coating = [[str(q.put_at), q.n_coating] for q in query]

    return render(request, 'report_day.html',
                  {'data': query, 'casting': data_casting, 'machining': data_machining, 'coating': data_coating})


# 月报表
def report_month(request):
    # 取时间
    dt = datetime.datetime.now()
    month = dt.month
    query = Wheel.objects.filter(put_at__month=month) \
        .values('put_at__day') \
        .annotate(sum_casting=Sum('n_casting'), sum_machining=Sum('n_machining'), sum_coating=Sum('n_coating'),
                  sum=Sum('n_sum'))
    data_chart = [[str(q['put_at__day']), q['sum']] for q in query]
    data_days = [str(i) for i in range(1, 32)]
    return render(request, 'report_month.html', {'data': query, 'chart': data_chart, 'days': data_days})
